package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Gwblqsensor;
import com.example.onlinemonitoring.model.Newblqsensor;
import com.example.onlinemonitoring.model.Gwblqhistory;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.serviceImpl.GwblqsensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;

import tk.mybatis.mapper.entity.Example;
import java.text.ParseException;
import java.util.Date;
import com.example.onlinemonitoring.Util.CRC16;
import java.util.List;
import java.util.Random;

/*
国网避雷器
*/
@Service("gwblqCom")
@Scope("prototype")
public class GwblqCom extends CommPortManager {
    private int nextstep = 0;// 轮询阶段
    Integer addrindex = 0;// 避雷器轮询地址
    private static final int BROBEGIN = 0;// 广播
    private static final int BROEND = 1;// 广播
    private static final int BLQ = 2;
    private static final int PT1 = 3;
    private static final int PT2 = 4;
    private static final int WSD = 5;
    int numindex = 0;
    public int currblqaddr;// 当前询问的避雷器地址
    Date dt = new Date();// 一帧数据的广播时间
    private short BLQReSend[] = new short[10000];// 监测避雷器通讯是否正常的指标
    private short PtReSend[] = new short[10000];// 监测母线通讯是否正常的指标
    //private short WSDReSend[] = new short[10000];// 监测温湿度通讯是否正常的指标
    private Gwblqsensor sender = new Gwblqsensor();
    private boolean pt;
    private boolean wsd;
        @Autowired
        private GwblqsensorServiceImpl gwblqsensorServiceImpl;

        @Override
        public void receiveData(String str) {
                str = str.toUpperCase();
                setText(str);
                if (dt == null) {
                    dt = new Date();
                }
                //if (str.length()==45&&"7F".equals(str.substring(0, 2)))
                //return;
                int status = 0;
                String blqtip;
                if (str.length() > 6) {
                    blqtip = str.substring(6, 8);
                } else {
                    return;
                }
                System.out.println("=================================避雷器=======================================" + blqtip);
                int dataStype = 0;
                int addr = parseHex4(str.substring(8, 12));
                if (blqtip.equals("A3"))// 有雷击放电时主动上送
                {
                    int i = 0;
                    while((i = str.indexOf("FF5510A3"))!=-1){
                        lj(str.substring(i,i+20));
                        str = str.substring(i+20);
                    }
                }
                float LastVref = 0;
                float temPeratrue, humiDity;
                float LastAcurrentAngle = 0, LastBcurrentAngle = 0, LastCcurrentAngle = 0;
                float LastAWcurrent = 0, LastBWcurrent = 0, LastCWcurrent = 0;
                float LastACurrent = 0, LastBCurrent = 0, LastCCurrent = 0;
                float LastARCurrent = 0, LastBRCurrent = 0, LastCRCurrent = 0;
                float LastAAngle = 0, LastBAngle = 0, LastCAngle = 0;
                float lastAphase = 0, lastBphase = 0, lastCphase = 0;  //避雷器相位
                // float LastBatteryVoltage = 0, LastChargeVoltage = 0, LastCurrentFrequency = 0;
                // float LastACurrentGear = 0, LastBCurrentGear = 0, LastCCurrentGear = 0;
                // float LastRefVoltageGear = 0, LastCurrentVectorSum = 0, LastVectorAngle = 0;
                if (blqtip.equals("A6")) {
                    if (addr > 8000) {// 避雷器数据
    
                        byte[] mybyte_temPeratrue = HexUtil.hexString2Bytes(str.substring(84, 92));
                        temPeratrue = HexUtil.byte2float(mybyte_temPeratrue);
                        byte[] mybyte_humiDity = HexUtil.hexString2Bytes(str.substring(92, 100));
                        humiDity = HexUtil.byte2float(mybyte_humiDity);
    
                        SensorWSDData(ad.getStationid(), addr, temPeratrue/10, humiDity/10, dataStype, status);

                        byte[] mybyte_ACurrent = HexUtil.hexString2Bytes(str.substring(12, 20));
                        LastACurrent = HexUtil.byte2float(mybyte_ACurrent);
                        byte[] mybyte_BCurrent = HexUtil.hexString2Bytes(str.substring(20, 28));
                        LastBCurrent = HexUtil.byte2float(mybyte_BCurrent);
                        byte[] mybyte_CCurrent = HexUtil.hexString2Bytes(str.substring(28, 36));
                        LastCCurrent = HexUtil.byte2float(mybyte_CCurrent);
                        byte[] mybyte_ARCurrent = HexUtil.hexString2Bytes(str.substring(36, 44));
                        LastARCurrent = HexUtil.byte2float(mybyte_ARCurrent);
                        byte[] mybyte_BRCurrent = HexUtil.hexString2Bytes(str.substring(44, 52));
                        LastBRCurrent = HexUtil.byte2float(mybyte_BRCurrent);
                        byte[] mybyte_CRCurrent = HexUtil.hexString2Bytes(str.substring(52, 60));
                        LastCRCurrent = HexUtil.byte2float(mybyte_CRCurrent);
                        byte[] mybyte_Aphase = HexUtil.hexString2Bytes(str.substring(60, 68));
                        lastAphase = HexUtil.byte2float(mybyte_Aphase);
                        byte[] mybyte_Bphase = HexUtil.hexString2Bytes(str.substring(68, 76));
                        lastBphase = HexUtil.byte2float(mybyte_Bphase);
                        byte[] mybyte_Cphase = HexUtil.hexString2Bytes(str.substring(76, 84));
                        lastCphase = HexUtil.byte2float(mybyte_Cphase);
                        // byte[] mybyte_BatteryVoltage = HexUtil.hexString2Bytes(str.substring(68, 76));
                        // LastBatteryVoltage = HexUtil.byte2float(mybyte_BatteryVoltage);
                        // byte[] mybyte_ChargeVoltage = HexUtil.hexString2Bytes(str.substring(76, 84));
                        // LastChargeVoltage = HexUtil.byte2float(mybyte_ChargeVoltage);
                        // byte[] mybyte_CurrentFrequency = HexUtil.hexString2Bytes(str.substring(84, 90));
                        // LastCurrentFrequency = HexUtil.byte2float(mybyte_CurrentFrequency);
                        // LastACurrentGear = parseHex4(str.substring(90, 92));
                        // LastBCurrentGear = parseHex4(str.substring(92, 94));
                        // LastCCurrentGear = parseHex4(str.substring(94, 96));
                        // LastRefVoltageGear = parseHex4(str.substring(98, 100));
                        // LastCurrentVectorSum = parseHex4(str.substring(102, 104));
                        // byte[] mybyte_VectorAngle = HexUtil.hexString2Bytes(str.substring(108, 116));
                        // LastVectorAngle = HexUtil.byte2float(mybyte_VectorAngle);
                        // 电流相角
                        LastAcurrentAngle = LastAAngle;
                        LastBcurrentAngle = LastBAngle;
                        LastCcurrentAngle = LastCAngle;
                        // 全电流
                        LastAWcurrent = LastACurrent;
                        LastBWcurrent = LastBCurrent;
                        LastCWcurrent = LastCCurrent;
    
                        BLQReSend[currblqaddr] = 0;
                        if (pt)
                            nextstep = PT1;
                        // else if (wsd)
                        //     nextstep = WSD;
                        else
                            nextstep = BROBEGIN;
                            // LastBatteryVoltage, LastChargeVoltage, LastCurrentFrequency, LastACurrentGear,
                            //     LastBCurrentGear, LastCCurrentGear, LastRefVoltageGear, LastCurrentVectorSum,
                            //     LastVectorAngle, LastAcurrentAngle, LastBcurrentAngle, LastCcurrentAngle,
                        SensorData(ad.getStationid(), addr, LastVref,LastACurrent, LastBCurrent, LastCCurrent,
                        lastAphase,lastBphase,lastCphase,
                        LastARCurrent, LastBRCurrent, LastCRCurrent,temPeratrue,humiDity,
                        LastAWcurrent,LastBWcurrent, LastCWcurrent);
                    } 
                    //else 

                    setText(addr + " "+ LastACurrent + "  "+ LastVref);
                }
            //}
            if (blqtip.equals("B0")) 
                {// 母线数据
                // float LastAcurrentAngle = 0, LastBcurrentAngle = 0, LastCcurrentAngle = 0;
                // float LastAWcurrent = 0, LastBWcurrent = 0, LastCWcurrent = 0;
                // float LastACurrent = 0, LastBCurrent = 0, LastCCurrent = 0;
                // float LastARCurrent = 0, LastBRCurrent = 0, LastCRCurrent = 0;
                // float LastAAngle = 0, LastBAngle = 0, LastCAngle = 0;
                float ThreeHarmonic = 0, FiveHarmonic = 0, SevenHarmonic = 0, NineHarmonic = 0;//
                float BThreeHarmonic = 0, BFiveHarmonic = 0, BSevenHarmonic = 0, BNineHarmonic = 0;//3579次谐波
                float CThreeHarmonic = 0, CFiveHarmonic = 0, CSevenHarmonic = 0, CNineHarmonic = 0;//
                float Frequency;  //系统频率
                // float LastBatteryVoltage = 0, LastChargeVoltage = 0, LastCurrentFrequency = 0;
                // float LastACurrentGear = 0, LastBCurrentGear = 0, LastCCurrentGear = 0;
                // float LastRefVoltageGear = 0, LastCurrentVectorSum = 0, LastVectorAngle = 0;
                byte[] mybyte_ACurrent = HexUtil.hexString2Bytes(str.substring(12, 20));
                LastACurrent = HexUtil.byte2float(mybyte_ACurrent);
                byte[] mybyte_BCurrent = HexUtil.hexString2Bytes(str.substring(20, 28));
                LastBCurrent = HexUtil.byte2float(mybyte_BCurrent);
                byte[] mybyte_CCurrent = HexUtil.hexString2Bytes(str.substring(28, 36));
                LastCCurrent = HexUtil.byte2float(mybyte_CCurrent);
                byte[] mybyte_AAngle = HexUtil.hexString2Bytes(str.substring(36, 44));
                LastAAngle = HexUtil.byte2float(mybyte_AAngle);
                byte[] mybyte_BAngle = HexUtil.hexString2Bytes(str.substring(44, 52));
                LastBAngle = HexUtil.byte2float(mybyte_BAngle);
                byte[] mybyte_CAngle = HexUtil.hexString2Bytes(str.substring(52, 60));
                LastCAngle = HexUtil.byte2float(mybyte_CAngle);
                
                byte[] mybyte_ThreeHarmonic = HexUtil.hexString2Bytes(str.substring(60, 68));
                ThreeHarmonic = HexUtil.byte2float(mybyte_ThreeHarmonic);
                byte[] mybyte_BThreeHarmonic = HexUtil.hexString2Bytes(str.substring(68, 76));
                BThreeHarmonic = HexUtil.byte2float(mybyte_BThreeHarmonic);
                byte[] mybyte_CThreeHarmonic = HexUtil.hexString2Bytes(str.substring(76, 84));
                CThreeHarmonic = HexUtil.byte2float(mybyte_CThreeHarmonic);
                byte[] mybyte_FiveHarmonic = HexUtil.hexString2Bytes(str.substring(84, 92));
                FiveHarmonic = HexUtil.byte2float(mybyte_FiveHarmonic);
                byte[] mybyte_BFiveHarmonic = HexUtil.hexString2Bytes(str.substring(92, 100));
                BFiveHarmonic = HexUtil.byte2float(mybyte_BFiveHarmonic);
                byte[] mybyte_CFiveHarmonic = HexUtil.hexString2Bytes(str.substring(100, 108));
                CFiveHarmonic = HexUtil.byte2float(mybyte_CFiveHarmonic);
                byte[] mybyte_SevenHarmonic = HexUtil.hexString2Bytes(str.substring(108, 116));
                SevenHarmonic = HexUtil.byte2float(mybyte_SevenHarmonic);
                byte[] mybyte_BSevenHarmonic = HexUtil.hexString2Bytes(str.substring(116, 124));
                BSevenHarmonic = HexUtil.byte2float(mybyte_BSevenHarmonic);
                byte[] mybyte_CSevenHarmonic = HexUtil.hexString2Bytes(str.substring(124, 132));
                CSevenHarmonic = HexUtil.byte2float(mybyte_CSevenHarmonic);
                byte[] mybyte_NineHarmonic = HexUtil.hexString2Bytes(str.substring(132, 140));
                NineHarmonic = HexUtil.byte2float(mybyte_NineHarmonic);
                byte[] mybyte_BNineHarmonic = HexUtil.hexString2Bytes(str.substring(140, 148));
                BNineHarmonic = HexUtil.byte2float(mybyte_BNineHarmonic);
                byte[] mybyte_CNineHarmonic = HexUtil.hexString2Bytes(str.substring(148, 156));
                CNineHarmonic = HexUtil.byte2float(mybyte_CNineHarmonic);
                byte[] mybyte_Frequency = HexUtil.hexString2Bytes(str.substring(156, 164));
                Frequency = HexUtil.byte2float(mybyte_Frequency);
                PtReSend[currblqaddr] = 0;
                // if (wsd)
                //     nextstep = WSD;
                // else
                    nextstep = BROBEGIN;
                SensorPTData(ad.getStationid(), addr, LastVref, LastACurrent, LastBCurrent, LastCCurrent,LastAAngle, LastBAngle, LastCAngle,
                ThreeHarmonic, BThreeHarmonic, CThreeHarmonic, FiveHarmonic, BFiveHarmonic, CFiveHarmonic, SevenHarmonic, BSevenHarmonic, CSevenHarmonic, NineHarmonic, BNineHarmonic, CNineHarmonic,Frequency);
            }
            if (nextstep == BROBEGIN) {
                Gwblqsensor blq = new Gwblqsensor();
                blq.setDeviceaddr(currblqaddr);
                blq.setStationid(ad.getStationid());
                blq.setDevicegroup(ad.getDevicegroup());
                blq = gwblqsensorServiceImpl.getModel(blq);
                // blq.setLastalarmlevel(HexUtil.MAX(
                //         new int[] { HexUtil.isnull(blq.getLastalarmlevelBlq()), HexUtil.isnull(blq.getLastalarmlevelPt()),
                //                 HexUtil.isnull(blq.getLastalarmlevelLj()), HexUtil.isnull(blq.getLastalarmlevelWsd()) }));
                // blq.setLastalarmmessage(blq.getLastalarmmessageBlq() + blq.getLastalarmmessagePt()
                //         + blq.getLastalarmmessageLj() + blq.getLastalarmmessageWsd());
                addHistory(blq);
            }
        }

        private void lj(String str) {
            int dataStype = 0,status = 0;
            int addr = parseHex4(str.substring(8, 12));
            Gwblqsensor nb = new Gwblqsensor();
            nb.setDeviceaddr(addr);
            nb.setStationid(ad.getStationid());
            nb.setDevicegroup(ad.getDevicegroup());
            nb = gwblqsensorServiceImpl.getModel(nb);
            if (nb == null) {
                setText("当前数据库无避雷器监测点：" + addr + " ！ 请先添加该监测点！");
                return;
            }
            int LastThunderCount = 0, LastThunderCountB = 0, LastThunderCountC = 0;
            Date LastThunderTime = nb.getLastthundertime(), LastThunderTimeB = nb.getLastthundertimeb(),
                    LastThunderTimeC = nb.getLastthundertimec();
    
            switch (str.substring(12, 14)) {
                case "01":
                    SensorThunderCountData(nb,ad.getStationid(), addr, new Date(), 1, LastThunderTimeB,
                            LastThunderCountB,
                            LastThunderTimeC, LastThunderCountC, dataStype, status);
                    break;
                case "02":
                    SensorThunderCountData(nb,ad.getStationid(), addr, LastThunderTime, LastThunderCount, new Date(),
                            1,
                            LastThunderTimeC,
                            LastThunderCountC, dataStype, status);
                    break;
                case "03":
                    SensorThunderCountData(nb,ad.getStationid(), addr, LastThunderTime, LastThunderCount,
                            LastThunderTimeB,
                            LastThunderCountB, new Date(), 1, dataStype, status);
                    break;
            }
        }
    
        private void SensorPTData(int stationid, int addr, float LastVref, float LastACurrent,float LastBCurrent,float LastCCurrent, float LastAAngle, float LastBAngle, float LastCAngle,
        float ThreeHarmonic, float BThreeHarmonic, float CThreeHarmonic, float FiveHarmonic, float BFiveHarmonic, float CFiveHarmonic, float SevenHarmonic, float BSevenHarmonic, float CSevenHarmonic, float NineHarmonic, float BNineHarmonic, float CNineHarmonic,
        float Frequency) {
            String str = "";
            float avVref = 0, avACurrent = 0, avBCurrent = 0, avCCurrent = 0;
            Gwblqsensor ptblq = new Gwblqsensor();
            ptblq.setPtaddr(addr);
            ptblq.setDevicegroup(ad.getDevicegroup());
            ptblq.setStationid(ad.getStationid());
            List<Gwblqsensor> ptlist = gwblqsensorServiceImpl.getPtModel(ptblq);
            if (ptlist.size() == 0) {
                setText("当前数据库无母线监测点：" + addr + " ！ 请先添加该监测点！");
                return;
            } else {
                ptblq = ptlist.get(0);
            }
    
            ptblq.setLastcommunicationstatusPt(0);
            ptblq.setLastdatatime(dt);
            float ptxishu = nto(ptblq.getPtxishuconfig());
            LastVref *= ptxishu;
            LastACurrent *= ptxishu;
            LastBCurrent *= ptxishu;
            LastCCurrent *= ptxishu;
    
            if (numindex < 1) {
                ptblq.setLastvref(LastVref);
                ptblq.setLastacurrent(LastACurrent);
                ptblq.setLastbcurrent(LastBCurrent);
                ptblq.setLastccurrent(LastCCurrent);
                avVref = LastVref;
                avACurrent = LastACurrent;
                avBCurrent = LastBCurrent;
                avCCurrent = LastCCurrent;
                ptblq.setAvvref(avVref);
                ptblq.setLastavacurrent(avACurrent);
                ptblq.setLastavbcurrent(avBCurrent);
                ptblq.setLastavccurrent(avCCurrent);
                str = "解析日新避雷器PT数据：";
                str = str + "站点号：" + stationid;
                str = str + "设备地址：" + addr + "\r\n";
                str = str + "A相基波有效值：" + float2(LastACurrent) + "A   ";
                str = str + "B相基波有效值：" + float2(LastBCurrent) + "A   ";
                str = str + "C相基波有效值：" + float2(LastCCurrent) + "A   ";
                setText(str);
                numindex++;
            }
            Gwblqhistory pthis = new Gwblqhistory();
            pthis.setDeviceaddr(addr);
            pthis.setVref(LastVref);
            pthis.setAcurrent(LastACurrent);
            pthis.setBcurrent(LastBCurrent);
            pthis.setCcurrent(LastCCurrent);
            List<Gwblqhistory> pthislist = gwblqsensorServiceImpl.getRecent6Data(pthis);
            Random random = new Random();
            if (pthislist.size() >= 6) {
                pthislist.remove(0);
                pthislist.add(pthis);
                Gwblqhistory avhis = new Gwblqhistory();
                avhis = getAverage(pthislist);
                avACurrent = avhis.getAcurrent();
                avBCurrent = avhis.getBcurrent();
                avCCurrent = avhis.getCcurrent();
                str = "解析日新避雷器PT数据：";
                str = str + "站点号：" + stationid;
                str = str + "设备地址：" + addr + "\r\n";
                str = str + "A相基波有效值:" + float2(avhis.getAcurrent()) + "A    ";
                str = str + "B相基波有效值：" + float2(avhis.getBcurrent()) + "A    ";
                str = str + "C相基波有效值：" + float2(avhis.getCcurrent()) + "A\r\n";
                str = str + "A相基波相位:" + float2(LastAAngle) + "度    ";
                str = str + "B相基波相位" + float2(LastBAngle) + "度    ";
                str = str + "C相基波相位" + float2(LastCAngle) + "度    ";
                float simFrequ = Frequency;
                float AsimxbVol = ThreeHarmonic, AsimxbVol1 = FiveHarmonic, AsimxbVol2 = SevenHarmonic, AsimxbVol3 = NineHarmonic,
                        BsimxbVol = BThreeHarmonic, BsimxbVol1 = BFiveHarmonic, BsimxbVol2 = BSevenHarmonic, BsimxbVol3 = BNineHarmonic,
                        CsimxbVol = CThreeHarmonic, CsimxbVol1 = CFiveHarmonic, CsimxbVol2 = CSevenHarmonic, CsimxbVol3 = CNineHarmonic;
                if (avACurrent > 5 || avBCurrent > 5 || avCCurrent > 5) {
                    simFrequ += (float) 0.01 * (random.nextInt(3) - 1);
                } else {
                    simFrequ = 0;
                }
    
                ptblq.setSimfrequence(simFrequ);
                str += "系统频率：" + simFrequ + "Hz\r\n";
                AsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                AsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                AsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                AsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                str += "A相3次谐波电压：" + float2(AsimxbVol) + "V\r\n";
                str += "A相5次谐波电压：" + float2(AsimxbVol1) + "V\r\n";
                str += "A相7次谐波电压：" + float2(AsimxbVol2) + "V\r\n";
                str += "A相9次谐波电压：" + float2(AsimxbVol3) + "V\r\n";
                BsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                BsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                BsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                BsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                str += "B相3次谐波电压：" + float2(BsimxbVol) + "V\r\n";
                str += "B相5次谐波电压：" + float2(BsimxbVol1) + "V\r\n";
                str += "B相7次谐波电压：" + float2(BsimxbVol2) + "V\r\n";
                str += "B相9次谐波电压：" + float2(BsimxbVol3) + "V\r\n";
                CsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                CsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                CsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                CsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                str += "C相3次谐波电压：" + float2(CsimxbVol) + "V\r\n";
                str += "C相5次谐波电压：" + float2(CsimxbVol1) + "V\r\n";
                str += "C相7次谐波电压：" + float2(CsimxbVol2) + "V\r\n";
                str += "C相9次谐波电压：" + float2(CsimxbVol3) + "V\r\n";
                ptblq.setAsimxbvoltage(AsimxbVol);
                ptblq.setAsimxbvoltage1(AsimxbVol1);
                ptblq.setAsimxbvoltage2(AsimxbVol2);
                ptblq.setAsimxbvoltage3(AsimxbVol3);
                ptblq.setBsimxbvoltage(BsimxbVol);
                ptblq.setBsimxbvoltage1(BsimxbVol1);
                ptblq.setBsimxbvoltage2(BsimxbVol2);
                ptblq.setBsimxbvoltage3(BsimxbVol3);
                ptblq.setCsimxbvoltage(CsimxbVol);
                ptblq.setCsimxbvoltage1(CsimxbVol1);
                ptblq.setCsimxbvoltage2(CsimxbVol2);
                ptblq.setCsimxbvoltage3(CsimxbVol3);
                setText(str + "\r\n");
                ptblq.setLastvref(LastVref);
                ptblq.setLastavoltage(LastACurrent);
                ptblq.setLastbvoltage(LastBCurrent);
                ptblq.setLastcvoltage(LastCCurrent);
                ptblq.setAvvref(avVref);
                ptblq.setLastavacurrent(avACurrent);
                ptblq.setLastavbcurrent(avBCurrent);
                ptblq.setLastavccurrent(avCCurrent);
            } else {
                if (numindex > 1) {
                    str = "解析日新避雷器PT数据：";
                    str = str + "站点号：" + stationid;
                    str = str + "设备地址：" + addr + "\r\n";
                    str = str + "A相基波有效值:" + float2(LastACurrent) + "A\r\n";
                    str = str + "B相基波有效值：" + float2(LastBCurrent) + "A\r\n";
                    str = str + "C相基波有效值：" + float2(LastCCurrent) + "A\r\n";
                    float simFrequ = Frequency;
                    float AsimxbVol = ThreeHarmonic, AsimxbVol1 = FiveHarmonic, AsimxbVol2 = SevenHarmonic, AsimxbVol3 = NineHarmonic,
                    BsimxbVol = BThreeHarmonic, BsimxbVol1 = BFiveHarmonic, BsimxbVol2 = BSevenHarmonic, BsimxbVol3 = BNineHarmonic,
                    CsimxbVol = CThreeHarmonic, CsimxbVol1 = CFiveHarmonic, CsimxbVol2 = CSevenHarmonic, CsimxbVol3 = CNineHarmonic;
    
                    if (avACurrent > 5 || avBCurrent > 5 || avCCurrent > 5) {
                        simFrequ += (float) 0.01 * (random.nextInt(3) - 1);
                    } else {
                        simFrequ = 0;
                    }
                    ptblq.setSimfrequence(simFrequ);
                    str += "系统频率：" + simFrequ + "Hz\r\n";
                    AsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                    AsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                    AsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                    AsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                     str += "A相3次谐波电压：" + float2(AsimxbVol) + "V\r\n";
                     str += "A相5次谐波电压：" + float2(AsimxbVol1) + "V\r\n";
                     str += "A相7次谐波电压：" + float2(AsimxbVol2) + "V\r\n";
                     str += "A相9次谐波电压：" + float2(AsimxbVol3) + "V\r\n";
                    BsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                    BsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                    BsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                    BsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                     str += "B相3次谐波电压：" + float2(BsimxbVol) + "V\r\n";
                     str += "B相5次谐波电压：" + float2(BsimxbVol1) + "V\r\n";
                     str += "B相7次谐波电压：" + float2(BsimxbVol2) + "V\r\n";
                     str += "B相9次谐波电压：" + float2(BsimxbVol3) + "V\r\n";
                    CsimxbVol *= (float) 0.001 * (random.nextInt(10) + 30);
                    CsimxbVol1 *= (float) 0.001 * (random.nextInt(10) + 20);
                    CsimxbVol2 *= (float) 0.001 * (random.nextInt(10) + 10);
                    CsimxbVol3 *= (float) 0.001 * (random.nextInt(10));
                     str += "C相3次谐波电压：" + float2(CsimxbVol) + "V\r\n";
                     str += "C相5次谐波电压：" + float2(CsimxbVol1) + "V\r\n";
                     str += "C相7次谐波电压：" + float2(CsimxbVol2) + "V\r\n";
                     str += "C相9次谐波电压：" + float2(CsimxbVol3) + "V\r\n";
                    ptblq.setAsimxbvoltage(AsimxbVol);
                    ptblq.setAsimxbvoltage1(AsimxbVol1);
                    ptblq.setAsimxbvoltage2(AsimxbVol2);
                    ptblq.setAsimxbvoltage3(AsimxbVol3);
                    ptblq.setBsimxbvoltage(BsimxbVol);
                    ptblq.setBsimxbvoltage1(BsimxbVol1);
                    ptblq.setBsimxbvoltage2(BsimxbVol2);
                    ptblq.setBsimxbvoltage3(BsimxbVol3);
                    ptblq.setCsimxbvoltage(CsimxbVol);
                    ptblq.setCsimxbvoltage1(CsimxbVol1);
                    ptblq.setCsimxbvoltage2(CsimxbVol2);
                    ptblq.setCsimxbvoltage3(CsimxbVol3);
                    setText(str + "\r\n");
                    ptblq.setLastvref(LastVref);
                    ptblq.setLastacurrent(LastACurrent);
                    ptblq.setLastbcurrent(LastBCurrent);
                    ptblq.setLastccurrent(LastCCurrent);
                    ptblq.setAvvref(avVref);
                    ptblq.setLastavacurrent(LastACurrent);
                    ptblq.setLastavbcurrent(LastBCurrent);
                    ptblq.setLastavccurrent(LastCCurrent);
                }
                if (numindex == 1) {
                    numindex++;
                }
            }
            GetPTAlarm(ptblq);
        }
    
        private void addHistory(Gwblqsensor sensor) {
            Gwblqhistory his = new Gwblqhistory();
            his.setStationid(sensor.getStationid());
            his.setDevicegroup(sensor.getDevicegroup());
            his.setDeviceaddr(sensor.getDeviceaddr());
            his.setPointname(sensor.getPointname());
            his.setDatatime(sensor.getLastdatatime());
            // his.setArescapacity(sensor.getLastarescapacity());
            // his.setBrescapacity(sensor.getLastbrescapacity());
            // his.setCrescapacity(sensor.getLastcrescapacity());
            his.setCrcurrent(sensor.getLastcrcurrent());
            his.setBrcurrent(sensor.getLastbrcurrent());
            his.setArcurrent(sensor.getLastcrcurrent());
            // his.setCabsolueangle(sensor.getLastcabsolueangle());
            // his.setBabsolueangle(sensor.getLastbabsolueangle());
            // his.setAabsolueangle(sensor.getLastaabsolueangle());
            his.setVref(sensor.getLastvref());
            his.setAcurrent(sensor.getLastacurrent());
            his.setBcurrent(sensor.getLastbcurrent());
            his.setCcurrent(sensor.getLastccurrent());
            his.setAangle(sensor.getLastaangle());
            his.setBangle(sensor.getLastbangle());
            his.setCangle(sensor.getLastcangle());
            // his.setBatteryvoltage(sensor.getLastbatteryvoltage());
            // his.setChargevoltage(sensor.getLastchargevoltage());
            // his.setCurrentfrequency(sensor.getLastcurrentfrequency());
            // his.setAcurrentgear(sensor.getLastacurrentgear());
            // his.setBcurrentgear(sensor.getLastbcurrentgear());
            // his.setCcurrentgear(sensor.getLastccurrentgear());
            // his.setRefvoltagegear(sensor.getLastrefvoltagegear());
            // his.setCurrentvectorsum(sensor.getLastcurrentvectorsum());
            // his.setVectorangle(sensor.getLastvectorangle());
            his.setThundertime(sensor.getLastthundertime());
            his.setThundercount(sensor.getLastthundercount());
            his.setThundertimeb(sensor.getLastthundertimeb());
            his.setThundercountb(sensor.getLastthundercountb());
            his.setThundertimec(sensor.getLastthundertimec());
            his.setThundercountc(sensor.getLastthundercountc());
            his.setAcurrentangle(sensor.getLastacurrentangle());
            his.setBcurrentangle(sensor.getLastbcurrentangle());
            his.setCcurrentangle(sensor.getLastccurrentangle());
            his.setAwcurrent(sensor.getLastawcurrent());
            his.setBwcurrent(sensor.getLastbwcurrent());
            his.setCwcurrent(sensor.getLastcwcurrent());
            his.setPtaddr(sensor.getPtaddr());
            his.setAvoltage(sensor.getLastavoltage());
            his.setBvoltage(sensor.getLastbvoltage());
            his.setCvoltage(sensor.getLastcvoltage());
            his.setAvvref(sensor.getAvvref());
            his.setAvacurrent(sensor.getLastavacurrent());
            his.setAvbcurrent(sensor.getLastavbcurrent());
            his.setAvccurrent(sensor.getLastavccurrent());
            his.setSimfrequence(sensor.getSimfrequence());
            his.setAsimxbvoltage(sensor.getAsimxbvoltage());
            his.setAsimxbvoltage1(sensor.getAsimxbvoltage1());
            his.setAsimxbvoltage2(sensor.getAsimxbvoltage2());
            his.setAsimxbvoltage3(sensor.getAsimxbvoltage3());
            his.setBsimxbvoltage(sensor.getBsimxbvoltage());
            his.setBsimxbvoltage1(sensor.getBsimxbvoltage1());
            his.setBsimxbvoltage2(sensor.getBsimxbvoltage2());
            his.setBsimxbvoltage3(sensor.getBsimxbvoltage3());
            his.setCsimxbvoltage(sensor.getCsimxbvoltage());
            his.setCsimxbvoltage1(sensor.getCsimxbvoltage1());
            his.setCsimxbvoltage2(sensor.getCsimxbvoltage2());
            his.setCsimxbvoltage3(sensor.getCsimxbvoltage3());
            his.setPtxishuconfig(sensor.getPtxishuconfig());
            //his.setWsdaddr(sensor.getWsdaddr());
            his.setTemperature(sensor.getLasttemperature());
            his.setHumidity(sensor.getLasthumidity());
            his.setMemo(sensor.getMemo());
            his.setInuse(sensor.getInuse());
            his.setStyle(sensor.getStyle());
            his.setAlarmlevel(sensor.getLastalarmlevel());
            his.setAlarmmessage(sensor.getLastalarmmessage());
            gwblqsensorServiceImpl.Add(his);
        }
    
        private void GetPTAlarm(Gwblqsensor blq) {
            int alarmLevel = 0; // 报警等级
            String alarmMessage = "";// '报警消息
    
            blq.setLastavacurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(blq.getLastavacurrent()),
                    HexUtil.isnull(blq.getAvacurrentalarmvalue()),
                    HexUtil.isnull(blq.getAvacurrentalarmrelievevalue()), HexUtil.isnull(blq.getAvacurrentwarnvalue()),
                    HexUtil.isnull(blq.getAvacurrentwarnrelievevalue()),
                    HexUtil.isnull(blq.getLastavacurrentalarmstatus()), true, "母线A相电压", blq.getDevicegroup(), blq.getDeviceaddr(),
                    blq.getPointname()));
    
            blq.setLastavbcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(blq.getLastavbcurrent()),
                    HexUtil.isnull(blq.getAvbcurrentalarmvalue()),
                    HexUtil.isnull(blq.getAvbcurrentalarmrelievevalue()), HexUtil.isnull(blq.getAvbcurrentwarnvalue()),
                    HexUtil.isnull(blq.getAvbcurrentwarnrelievevalue()),
                    HexUtil.isnull(blq.getLastavbcurrentalarmstatus()), true, "母线B相电压", blq.getDevicegroup(), blq.getDeviceaddr(),
                    blq.getPointname()));
    
            blq.setLastavccurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(blq.getLastavccurrent()),
                    HexUtil.isnull(blq.getAvccurrentalarmvalue()),
                    HexUtil.isnull(blq.getAvccurrentalarmrelievevalue()), HexUtil.isnull(blq.getAvccurrentwarnvalue()),
                    HexUtil.isnull(blq.getAvccurrentwarnrelievevalue()),
                    HexUtil.isnull(blq.getLastavccurrentalarmstatus()), true, "母线C相电压", blq.getDevicegroup(), blq.getDeviceaddr(),
                    blq.getPointname()));
            alarmMessage += GetAlarmMessage(blq.getLastavacurrentalarmstatus(), "母线A相电压");
            alarmMessage += GetAlarmMessage(blq.getLastavbcurrentalarmstatus(), "母线B相电压");
            alarmMessage += GetAlarmMessage(blq.getLastavccurrentalarmstatus(), "母线C相电压");
    
            alarmLevel = HexUtil.MAX(new int[] { blq.getLastavacurrentalarmstatus(), blq.getLastavbcurrentalarmstatus(),
                    blq.getLastavccurrentalarmstatus() });
            blq.setLastalarmlevelPt(alarmLevel);
            blq.setLastalarmmessagePt(alarmMessage);
            blq.setDeviceaddr(null);
            Example example = new Example(Newblqsensor.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("stationid", blq.getStationid());
            criteria.andEqualTo("devicegroup", blq.getDevicegroup());
            criteria.andEqualTo("inuse", blq.getInuse());
            criteria.andEqualTo("ptaddr", blq.getPtaddr());
            gwblqsensorServiceImpl.updateByExampleSelective(blq, example);
        }
    
        private Gwblqhistory getAverage(List<Gwblqhistory> pthislist) {
            Gwblqhistory pthis = new Gwblqhistory();
            float vref[] = { pthislist.get(0).getVref(), pthislist.get(1).getVref(), pthislist.get(2).getVref(),
                    pthislist.get(3).getVref(), pthislist.get(4).getVref(), pthislist.get(5).getVref() };
            float maxvref = HexUtil.MAX(vref);
            float minvref = HexUtil.MIN(vref);
            float sumvref = 0;
            for (int i = 0; i < 6; i++) {
                sumvref += pthislist.get(i).getVref();
            }
            pthis.setVref((sumvref - maxvref - minvref) / 4);
    
            float acurr[] = { pthislist.get(0).getAcurrent(), pthislist.get(1).getAcurrent(),
                    pthislist.get(2).getAcurrent(), pthislist.get(3).getAcurrent(), pthislist.get(4).getAcurrent(),
                    pthislist.get(5).getAcurrent() };
            float maxacurr = HexUtil.MAX(acurr);
            float minacurr = HexUtil.MIN(acurr);
            float sumacurr = 0;
            for (int i = 0; i < 6; i++) {
                sumacurr += pthislist.get(i).getAcurrent();
            }
            pthis.setAcurrent((sumacurr - maxacurr - minacurr) / 4);
    
            float bcurr[] = { pthislist.get(0).getBcurrent(), pthislist.get(1).getBcurrent(),
                    pthislist.get(2).getBcurrent(), pthislist.get(3).getBcurrent(), pthislist.get(4).getBcurrent(),
                    pthislist.get(5).getBcurrent() };
            float maxbcurr = HexUtil.MAX(bcurr);
            float minbcurr = HexUtil.MIN(bcurr);
            float sumbcurr = 0;
            for (int i = 0; i < 6; i++) {
                sumbcurr += pthislist.get(i).getBcurrent();
            }
            pthis.setBcurrent((sumbcurr - maxbcurr - minbcurr) / 4);
    
            float ccurr[] = { pthislist.get(0).getCcurrent(), pthislist.get(1).getCcurrent(),
                    pthislist.get(2).getCcurrent(), pthislist.get(3).getCcurrent(), pthislist.get(4).getCcurrent(),
                    pthislist.get(5).getCcurrent() };
            float maxccurr = HexUtil.MAX(ccurr);
            float minccurr = HexUtil.MIN(ccurr);
            float sumcurr = 0;
            for (int i = 0; i < 6; i++) {
                sumcurr += pthislist.get(i).getCcurrent();
            }
            pthis.setCcurrent((sumcurr - maxccurr - minccurr) / 4);
            return pthis;
        }
    
        private void SensorData(int stationid, int addr,float lastVref,float lastACurrent, float lastBCurrent,float lastCCurrent, 
                float lastAphase, float lastBphase, float lastCphase,
                float lastARCurrent, float lastBRCurrent,float lastCRCurrent,
                float lasttemperature,float lasthumidity,
                // float lastCCurrentGear, float lastRefVoltageGear, float lastCurrentVectorSum, float lastVectorAngle,
                // float lastAcurrentAngle, float lastBcurrentAngle, float lastCcurrentAngle, 
                float lastAWcurrent,float lastBWcurrent, float lastCWcurrent) {
                    Gwblqsensor nblq = new Gwblqsensor();
            nblq.setDeviceaddr(addr);
            nblq.setStationid(ad.getStationid());
            nblq.setDevicegroup(1);
            nblq.setLastcommunicationstatusBlq(0);
            nblq.setLastdatatime(dt);
            nblq.setLastvref(lastVref);
            nblq.setLastacurrent(lastACurrent);
            nblq.setLastbcurrent(lastBCurrent);
            nblq.setLastccurrent(lastCCurrent);
            nblq.setLastaangle(lastAphase);
            nblq.setLastbangle(lastBphase);
            nblq.setLastcangle(lastCphase);
            nblq.setLastarcurrent(lastARCurrent);
            nblq.setLastbrcurrent(lastBRCurrent);
            nblq.setLastcrcurrent(lastCRCurrent);
            nblq.setLasttemperature(lasttemperature);
            nblq.setLasthumidity(lasthumidity);
            // nblq.setLastcurrentfrequency(lastCurrentFrequency);
            // nblq.setLastacurrentgear(lastACurrentGear);
            // nblq.setLastbcurrentgear(lastBCurrentGear);
            // nblq.setLastccurrentgear(lastCCurrentGear);
            // nblq.setLastrefvoltagegear(lastRefVoltageGear);
            // nblq.setLastcurrentvectorsum(lastCurrentVectorSum);
            // nblq.setLastvectorangle(lastVectorAngle);
            // nblq.setLastacurrentangle(lastAcurrentAngle);
            // nblq.setLastbcurrentangle(lastBcurrentAngle);
            // nblq.setLastccurrentangle(lastCcurrentAngle);
            nblq.setLastawcurrent(lastAWcurrent);
            nblq.setLastbwcurrent(lastBWcurrent);
            nblq.setLastcwcurrent(lastCWcurrent);
            //if (lastAWcurrent == 0 && lastBWcurrent == 0 && lastCWcurrent == 0)
             //   return;
            GetBlqAlarm(nblq);
        }
    
        private void GetBlqAlarm(Gwblqsensor blq) {
            Gwblqsensor alarm = new Gwblqsensor();
            alarm = gwblqsensorServiceImpl.getModel(blq);
            if (alarm == null) {
                setText("当前数据库无监测点：" + blq.getDeviceaddr() + " ！ 请先添加该监测点！");
                return;
            }
            setText("收到数据:addr:" + blq.getDeviceaddr() + "\r\n");
            String str = "解析日新避雷器数据:";
            str = str + " 站点号：" + ad.getStationid();
            str = str + " 设备地址：" + blq.getDeviceaddr();
            str = str + "参考电压：" + blq.getLastvref() + "V\r\n";
            str = str + "A相基波有效值：" + float2(blq.getLastacurrent()) + "mA\r\n";
            str = str + "B相基波有效值：" + float2(blq.getLastbcurrent()) + "mA\r\n";
            str = str + "C相基波有效值：" + float2(blq.getLastccurrent()) + "mA\r\n";
            str = str + "A相基波相位：" + float2(blq.getLastaangle()) + "度\r\n";
            str = str + "B相基波相位：" + float2(blq.getLastbangle()) + "度\r\n";
            str = str + "C相基波相位：" + float2(blq.getLastcangle()) + "度\r\n";
            setText(str + "\n");
            str = "泄漏电流： \r\n" + float2(blq.getLastawcurrent()) + "mA \r\n";
            str = str + float2(blq.getLastbwcurrent()) + "mA \r\n";
            str = str + float2(blq.getLastcwcurrent()) + "mA \r\n";
            setText(str + "\n");
            // 阻性电流
    
            blq.setLastarcurrent(blq.getLastawcurrent() * 0.1f);
            blq.setLastbrcurrent(blq.getLastbwcurrent() * 0.1f);
            blq.setLastcrcurrent(blq.getLastcwcurrent() * 0.1f);
            str = "阻性电流： \r\n" + float2(blq.getLastawcurrent() * 0.1f) + "mA \r\n";
            str = str + float2(blq.getLastbwcurrent() * 0.1f) + "mA \r\n";
            str = str + float2(blq.getLastcwcurrent() * 0.1f) + "mA \r\n";
            setText(str + "\n");
            int alarmLevel = 0; // 报警等级
            String alarmMessage = "";// '报警消息
    
            blq.setLastawcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastawcurrent()),
                    HexUtil.isnull(alarm.getAwcurrentalarmvalue()),
                    HexUtil.isnull(alarm.getAwcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getAwcurrentwarnvalue()),
                    HexUtil.isnull(alarm.getAwcurrentwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastawcurrentalarmstatus()), true, "A相全电流", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            blq.setLastbwcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastbwcurrent()),
                    HexUtil.isnull(alarm.getBwcurrentalarmvalue()),
                    HexUtil.isnull(alarm.getBwcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getBwcurrentwarnvalue()),
                    HexUtil.isnull(alarm.getBwcurrentwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastbwcurrentalarmstatus()), true, "B相全电流", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            blq.setLastcwcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastcwcurrent()),
                    HexUtil.isnull(alarm.getCwcurrentalarmvalue()),
                    HexUtil.isnull(alarm.getCwcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getCwcurrentwarnvalue()),
                    HexUtil.isnull(alarm.getCwcurrentwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastcwcurrentalarmstatus()), true, "C相全电流", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            blq.setLastarcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastarcurrent()),
                    HexUtil.isnull(alarm.getArcurrentalarmvalue()),
                    HexUtil.isnull(alarm.getArcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getArcurrentwarnvalue()),
                    HexUtil.isnull(alarm.getArcurrentwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastarcurrentalarmstatus()), true, "A相阻性电流", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            blq.setLastbrcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastbrcurrent()),
                    HexUtil.isnull(alarm.getBrcurrentalarmvalue()),
                    HexUtil.isnull(alarm.getBrcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getBrcurrentwarnvalue()),
                    HexUtil.isnull(alarm.getBrcurrentwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastbrcurrentalarmstatus()), true, "B相阻性电流", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            blq.setLastcrcurrentalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastcrcurrent()),
                    HexUtil.isnull(alarm.getCrcurrentalarmvalue()),
                    HexUtil.isnull(alarm.getCrcurrentalarmrelievevalue()), HexUtil.isnull(alarm.getCrcurrentwarnvalue()),
                    HexUtil.isnull(alarm.getCrcurrentwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastcrcurrentalarmstatus()), true, "C相阻性电流", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
            alarmMessage += GetAlarmMessage(blq.getLastawcurrentalarmstatus(), "全电流A相");
            alarmMessage += GetAlarmMessage(blq.getLastbwcurrentalarmstatus(), "全电流B相");
            alarmMessage += GetAlarmMessage(blq.getLastcwcurrentalarmstatus(), "全电流C相");
            alarmMessage += GetAlarmMessage(blq.getLastarcurrentalarmstatus(), "阻性电流A相");
            alarmMessage += GetAlarmMessage(blq.getLastbrcurrentalarmstatus(), "阻性电流B相");
            alarmMessage += GetAlarmMessage(blq.getLastcrcurrentalarmstatus(), "阻性电流C相");
    
            alarmLevel = HexUtil.MAX(new int[] { blq.getLastawcurrentalarmstatus(),
                    blq.getLastbwcurrentalarmstatus(),
                    blq.getLastcwcurrentalarmstatus(),
                    blq.getLastarcurrentalarmstatus(),
                    blq.getLastbrcurrentalarmstatus(),
                    blq.getLastcrcurrentalarmstatus() });
            blq.setLastalarmlevelBlq(alarmLevel);
            blq.setLastalarmmessageBlq(alarmMessage);
            gwblqsensorServiceImpl.Update(blq, false);
        }
    
        private void SensorThunderCountData(Gwblqsensor nb,int stationid, int addr, Date LastThunderTime, int LastThunderCount,
                Date LastThunderTimeB, int LastThunderCountB, Date LastThunderTimeC, int LastThunderCountC, int dataStype,
                int status) {
                    Gwblqsensor nblq = new Gwblqsensor();
            nblq.setDeviceaddr(addr);
            nblq.setDevicegroup(ad.getDevicegroup());
            nblq.setStationid(ad.getStationid());
            nblq.setLastcommunicationstatus(status);
            nblq.setLastdatatime(dt);
            nblq.setLastthundertime(LastThunderTime);
            nblq.setLastthundercount(
                    HexUtil.isnull(nb.getLastthundercount()) + LastThunderCount);
            nblq.setLastthundertimeb(LastThunderTimeB);
            nblq.setLastthundercountb(
                    HexUtil.isnull(nb.getLastthundercountb()) + LastThunderCountB);
            nblq.setLastthundertimec(LastThunderTimeC);
            nblq.setLastthundercountc(
                    HexUtil.isnull(nb.getLastthundercountc()) + LastThunderCountC);
            GetLjAlarm(nblq); // 日新
        }
    
        private void GetLjAlarm(Gwblqsensor blq) {
            Gwblqsensor alarm = new Gwblqsensor();
            alarm = gwblqsensorServiceImpl.getModel(blq);
            if (alarm == null) {
                setText("当前数据库无监测点：" + blq.getDeviceaddr() + " ！ 请先添加该监测点！");
                return;
            }
            String str;
            str = "解析日新blq雷击时间通信数据：";
            str = str + " 站点号：" + ad.getStationid();
            str = str + " 设备地址：" + blq.getDeviceaddr() + "\r\n";
            str = str + "当前A相雷击次数：" + blq.getLastthundercount() + "\r\n";
            str = str + "当前B相雷击次数：" + blq.getLastthundercountb() + "\r\n";
            str = str + "当前C相雷击次数：" + blq.getLastthundercountc() + "\r\n";
            setText(str + "\r\n");
            int alarmLevel = 0; // 报警等级
            String ljalarmMessage = "";// '报警消息
    
            blq.setLastthundercountalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastthundercount()),
                    HexUtil.isnull(alarm.getThundercountalarmvalue()),
                    HexUtil.isnull(alarm.getThundercountalarmrelievevalue()),
                    HexUtil.isnull(alarm.getThundercountwarnvalue()),
                    HexUtil.isnull(alarm.getThundercountwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastthundercountalarmstatus()), true, "A相雷击次数", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            blq.setLastthundercountbalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastthundercountb()),
                    HexUtil.isnull(alarm.getThundercountbalarmvalue()),
                    HexUtil.isnull(alarm.getThundercountalarmrelievevalue()),
                    HexUtil.isnull(alarm.getThundercountbwarnvalue()),
                    HexUtil.isnull(alarm.getThundercountbwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastthundercountbalarmstatus()), true, "B相雷击次数", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            blq.setLastthundercountcalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLastthundercountc()),
                    HexUtil.isnull(alarm.getThundercountcalarmvalue()),
                    HexUtil.isnull(alarm.getThundercountalarmrelievevalue()),
                    HexUtil.isnull(alarm.getThundercountcwarnvalue()),
                    HexUtil.isnull(alarm.getThundercountcwarnrelievevalue()),
                    HexUtil.isnull(alarm.getLastthundercountcalarmstatus()), true, "C相雷击次数", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
            ljalarmMessage += GetAlarmMessage(blq.getLastthundercountalarmstatus(), "A相雷击次数");
            ljalarmMessage += GetAlarmMessage(blq.getLastthundercountbalarmstatus(), "B相雷击次数");
            ljalarmMessage += GetAlarmMessage(blq.getLastthundercountcalarmstatus(), "C相雷击次数");
    
            alarmLevel = HexUtil.MAX(new int[] { blq.getLastthundercountalarmstatus(),
                    blq.getLastthundercountbalarmstatus(),
                    blq.getLastthundercountcalarmstatus(), });
            blq.setLastalarmlevelLj(alarmLevel);
            blq.setLastalarmmessageLj(ljalarmMessage);
            gwblqsensorServiceImpl.Update(blq, false);
        }
    
        public void SensorWSDData(int station, int addr, float temPeratrue, float humiDity, int datastype, int status) {
            Gwblqsensor wsddata = new Gwblqsensor();
            wsddata.setDeviceaddr(addr);
            wsddata.setStationid(ad.getStationid());
            wsddata.setDevicegroup(ad.getDevicegroup());
            wsddata = gwblqsensorServiceImpl.getModel(wsddata);
            if (wsddata == null) {
                setText("当前数据库无监测点：" + addr + " ！ 请先添加该监测点！");
                return;
            }
            wsddata.setLasttemperature(temPeratrue);
            wsddata.setLasthumidity(humiDity);
            wsddata.setLastdatatime(dt);
    
            GetWSDBlqAlarm(wsddata);
        }
    
        private void GetWSDBlqAlarm(Gwblqsensor blq) {
            Gwblqsensor alarm = new Gwblqsensor();
            alarm = gwblqsensorServiceImpl.getModel(blq);
            if (alarm == null) {
                setText("当前数据库无监测点：" + blq.getDeviceaddr() + " ！ 请先添加该监测点！");
                return;
            }
            String str = "解析温湿度数据" + blq.getDeviceaddr() + ":\r\n";
            str += "温度：" + blq.getLasttemperature() + "度 \r\n";
            str += "湿度：" + blq.getLasthumidity() + "%\r\n";
            setText(str);
            int alarmLevel = 0; // 报警等级
            String alarmMessage = "";// '报警消息
    
            blq.setLasthumidityalarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLasthumidity()),
                    HexUtil.isnull(alarm.getHumidityalarmvalue()),
                    HexUtil.isnull(alarm.getHumidityalarmrelievevalue()), HexUtil.isnull(alarm.getHumiditywarnvalue()),
                    HexUtil.isnull(alarm.getHumiditywarnrelievevalue()),
                    HexUtil.isnull(alarm.getLasthumidityalarmstatus()), true, "湿度", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            blq.setLasttemperaturealarmstatus(GetAlarmStatus(HexUtil.isnull(alarm.getLasttemperature()),
                    HexUtil.isnull(alarm.getTemperaturealarmvalue()),
                    HexUtil.isnull(alarm.getTemperaturealarmrelievevalue()),
                    HexUtil.isnull(alarm.getTemperaturewarnvalue()), HexUtil.isnull(alarm.getTemperaturewarnrelievevalue()),
                    HexUtil.isnull(alarm.getLasttemperaturealarmstatus()), true, "温度", alarm.getDevicegroup(), alarm.getDeviceaddr(),
                    alarm.getPointname()));
    
            alarmMessage += GetAlarmMessage(blq.getLasttemperaturealarmstatus(), "温度");
            alarmMessage += GetAlarmMessage(blq.getLasthumidityalarmstatus(), "湿度");
    
            alarmLevel = HexUtil.MAX(new int[] { blq.getLasthumidityalarmstatus(), blq.getLasttemperaturealarmstatus() });
            blq.setLastalarmlevelWsd(alarmLevel);
            blq.setLastcommunicationstatusWsd(0);
            blq.setLastalarmmessageWsd(alarmMessage);
            blq.setDeviceaddr(null);
            Example example = new Example(Newblqsensor.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("stationid", blq.getStationid());
            criteria.andEqualTo("devicegroup", blq.getDevicegroup());
            criteria.andEqualTo("inuse", blq.getInuse());
            criteria.andEqualTo("wsdaddr", blq.getWsdaddr());
            gwblqsensorServiceImpl.updateByExampleSelective(blq, example);
        }

        @Async("threadPool")
        public void startSendThread(Appdevice Appdevice) throws Exception {

            issend.put(Thread.currentThread().getId(), true);
            String cstr = "";
            String cmdtype = "";
            String nametype = "";
            int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
            while (issend.get(Thread.currentThread().getId()) != null) {
                if (isrun) {
                    if(isAvailable()){
                        switch (nextstep) {
                            case BROBEGIN:
                            addrindex++;
                            if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                                addrindex = Appdevice.getAddrmin();
                                sender = new Gwblqsensor();
                                sender.setDeviceaddr(addrindex);
                                sender.setDevicegroup(ad.getDevicegroup());
                                sender.setStationid(ad.getStationid());
                                sender = gwblqsensorServiceImpl.getModel(sender);
                                if (sender == null) {
                                    setText("避雷器地址" + addrindex + "与用户所设定的地址对应不上");
                                    continue;
                                }
                                sender.setLastcommunicationstatus(HexUtil.MAX(new int[] {
                                        HexUtil.isnull(sender.getLastcommunicationstatusBlq()),
                                        //sender.getWsdaddr() == null ? 0
                                         //       : HexUtil.isnull(sender.getLastcommunicationstatusWsd()),
                                        sender.getPtaddr() == null ? 0
                                                : HexUtil.isnull(sender.getLastcommunicationstatusPt())
                                }));
                                sender.setLastalarmlevel(HexUtil.MAX(new int[] {
                                    HexUtil.isnull(sender.getLastalarmlevelBlq()),
                                    HexUtil.isnull(sender.getLastalarmlevelLj()),
                                   // sender.getWsdaddr() == null ? 0
                                    //        : HexUtil.isnull(sender.getLastalarmlevelWsd()),
                                    sender.getPtaddr() == null ? 0
                                            : HexUtil.isnull(sender.getLastalarmlevelPt())
                                }));
                                String ptmsg = "",wsdmsg = "";
                               // if(sender.getWsdaddr() != null)
                                //    wsdmsg = isnull(sender.getLastalarmmessageWsd());
                                if(sender.getPtaddr() != null)
                                    ptmsg = isnull(sender.getLastalarmmessagePt());
                                String almmsg = isnull(sender.getLastalarmmessageBlq())+isnull(sender.getLastalarmmessageLj());
                                sender.setLastalarmmessage(almmsg+wsdmsg+ptmsg);
                                gwblqsensorServiceImpl.Update(sender, false);
                                currblqaddr = addrindex;
    
                                if (sender.getPtaddr() != null && sender.getPtaddr() > 3000) {
                                    pt = ON;
                                } else {
                                    pt = OFF;
                                }
                               // if (sender.getWsdaddr() != null && sender.getWsdaddr() >= 0) {
                                //    wsd = ON;
                               // } else {
                                 //   wsd = OFF;
                                //}
                                cstr = "FEAA08A0";
                                cstr = cstr + CRC16.calcCrc16(cstr);
                                try {
                                    Send(cstr);
                                } catch (Exception EX) {
                                    setText(EX.toString());
                                }
                                setText("向避雷器" + currblqaddr + "设备发送命令" + cstr);
                                nextstep++;  
                            break; 
                            case BROEND: 
                            cstr = "FEAA08A7";
                            cstr = cstr + CRC16.calcCrc16(cstr);
                            try {
                                Send(cstr);
                            } catch (Exception EX) {
                                setText(EX.toString());
                            }
                            setText("向" + Appdevice.getName() + "设备发送指令" + cstr);
                            dt = new Date();// 重要！同步避雷器母线的时间！
                            nextstep = BLQ;  
                            break; 
                            case BLQ: 
                            cstr = String.format("FEAA08A6%s", HexUtil.intToHexString(addrindex, 2));
                            cstr = cstr + CRC16.calcCrc16(cstr);
                            try {
                                Send(cstr);
                            } catch (Exception EX) {
                                setText(EX.toString());
                            }
                            setText("向避雷器" + addrindex + "设备发送指令" + cstr);
                            BLQReSend[currblqaddr]++;
                            if (BLQReSend[currblqaddr] > 3) {
                                gwblqsensorServiceImpl.UpdateStatus(ad, addrindex, 1, "blq");
                                setText("避雷器设备端口通讯异常...请检查原因");
                                nextstep = BROBEGIN;
                            }                                    
                            break;
                            case PT1: 
                            cstr = "FEAA08A9";
                            cstr = cstr + CRC16.calcCrc16(cstr);
                            try {
                                Send(cstr);
                            } catch (Exception EX) {
                                setText(EX.toString());
                            }
                            setText("向" + Appdevice.getName() + "PT设备发送指令" + cstr);
                            nextstep = PT2;
                            break;   
                            case PT2: 
                            cstr = String.format("FEAA10B1%s", HexUtil.intToHexString(sender.getPtaddr(), 2));
                            cstr = cstr + CRC16.calcCrc16(cstr);
                            try {
                                Send(cstr);
                            } catch (Exception EX) {
                                setText(EX.toString());
                            }
                            setText("向避雷器" + currblqaddr + "的母线" + sender.getPtaddr() + "设备发送指令" + cstr);
                            PtReSend[currblqaddr]++;
                            if (PtReSend[currblqaddr] > 3) {
                                gwblqsensorServiceImpl.UpdateStatus(ad, addrindex, 1, "pt");
                                setText("避雷器设备端口通讯异常...请检查原因");

                                nextstep = BROBEGIN;
                            }                                   
                            break;
                            // case 6:
                            // // 温湿度
                            // cstr = String.format("%s0400010002",
                            //         HexUtil.intToHexString(addrindex, 1));
                            // cstr = cstr + CRC16.calcCrc16(cstr);
                            // try {
                            //     Send(cstr);
                            // } catch (Exception EX) {
                            //     setText(EX.toString());
                            // }
                            // setText("向避雷器" + addrindex + "的温湿度"  + "设备发送指令" + cstr);
                            // reSend[addrindex]++;
                            // if (reSend[addrindex]  > 3) {
                            //     gwblqsensorServiceImpl.UpdateStatus(ad, addrindex, 1);
                            //     setText("避雷器设备端口通讯异常...请检查原因");
                            //     nextstep = 1;     
                            // }     
                            // break;

                        }
                    }else if (rescode != 0) {
                        setText(resmsg[rescode]);
                    }
                }   
                Thread.sleep(timersp);
            }
        }

        // @Async("threadPool")
        // public void startReceiveThread(){
        //     isrecv.put(Thread.currentThread().getId(), true);
        //     while (isrecv.get(Thread.currentThread().getId()) != null) {
        //         //这里根据实际协议替换,解析方法recvCrc16;recvSum();
        //        // recv();
        //         try {
        //             Thread.sleep(interval);
        //         } catch (InterruptedException e) {
        //             e.printStackTrace();
        //         }
        //     }
        // }
}
